package com.cheyunkeji.er;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.cheyun.netsalev3.BuildConfig;
import com.cheyunkeji.er.activity.LoginActivity;
import com.cheyunkeji.er.app.GlobalConfig;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.bean.CarIds;
import com.cheyunkeji.er.bean.evaluate.CarTempAttrList;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.SerializeUtil;
import com.cheyunkeji.er.utils.version.UpdateVersionUtils;
import com.igexin.sdk.IUserLoggerInterface;
import com.igexin.sdk.PushManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//import androidx.multidex.MultiDex;


/**
 * Created by Administrator on 2017/2/13.
 */

public class MyApplication extends Application {

    //实例对象
    private static MyApplication myApplication;
    private static CarIds car300Ids;
    private static OssService ossService = null;
    private static OSS oss = null;
    //   缓存车辆字段列表数据
    private static CarTempAttrList attrList = null;
    //   缓存车辆字段列表数据
//    private static CarBasicInfoList basicList = null;
    //    缓存评估结果
    private static EvaluateDetailResult2 evaluateResult;
    //当前版本
    public int app_version;

    public static int getCurrentModuleType() {
        return UserInfoManager.getInstance(getInstance()).getCurrentModuleType();
    }

    public static void setCurrentModuleType(int currentModuleType) {
        UserInfoManager.getInstance(getInstance()).saveCurrentModuleType(currentModuleType);
    }

    /**
     * 当前选中模块flag
     */
    public static String phone = ""; //当前临时保存的手机号码
    public static String pwd = "";//保存当前密码
    /**
     * 保存app当前所有存活的Activity
     */
    private List<Activity> acts;

    //个推相关
    public static StringBuilder payloadData = new StringBuilder();
    private static PushHandler handler;

//    public static OssService getOssService(OssService.onImageProcessedResultListener listener) {
//
//        if (null == ossService) {
//            synchronized (MyApplication.class) {
//                ossService = new OssService(getOss(), HttpConstants.ALIYUN_OSS_BUCKET, listener);
//            }
//        }
//        ossService.setOnImageProcessedResultListener(listener);
//        return ossService;
//    }
//
//    public static OSS getOss() {
//
//        if (null == oss) {
//            synchronized (MyApplication.class) {
//                OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpConstants.OSS_ACCESS_KEYID, HttpConstants.OSS_ACCESS_KEY_SECRET);
//                ClientConfiguration conf = new ClientConfiguration();
//                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
//                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
//                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
//                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
//                oss = new OSSClient(MyApplication.getInstance().getApplicationContext(), HttpConstants.OSS_END_POINT, credentialProvider, conf);
//            }
//        }
//        return oss;
//    }

    public static MyApplication getInstance() {
        return myApplication;
    }

    public static CarIds getCar300Ids() {
        return car300Ids;
    }

    public boolean hasCheckVersion = false;

    public static CarTempAttrList getCarTempAttrList() {
        if (null == attrList) {
            return SerializeUtil.getCarTempAttrList();
        }
        return attrList;
    }


    public static EvaluateDetailResult2 getEvaluateResult() {
//        if (evaluateResult == null)
//            return SerializeUtil.getEvaluateDetailResult();
        return evaluateResult;
    }




    /**
     * 记录当前在前台的Activity个数，不为0则表示在前台运行，为0则表示在后台运行
     */
    private int appCount = 0;

    public static void sendMessage(Message msg) {
        handler.sendMessage(msg);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化实例
        myApplication = this;
        //初始化页面列表
        acts = new ArrayList<>();

        car300Ids = new CarIds();
        //获取当前版本
        PackageInfo packageInfo = UpdateVersionUtils.getPackageInfo(this);
        app_version = packageInfo.versionCode;
        initBugly();

        initUmengAnalytics();
        /**
         * 设置组件化的Log开关
         * 参数: boolean 默认为false，如需查看LOG设置为true
         */
//        UMConfigure.setLogEnabled(true);
//        UMConfigure.init(this, HttpConstants.UmengAppKey, "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        //微信APPID和AppSecret
//        PlatformConfig.setWeixin(HttpConstants.WeixinAppId,HttpConstants.WeixinAppSecret);

        //个推推送
        if (handler == null) {
            handler = new PushHandler();
        }
        initPushSdk();

        OSSLog.enableLog();

        /**
         * 注册生命周期回调，用于判断当前应用是否在前台
         */
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                appCount++;
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                appCount--;
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    private void initPushSdk() {

        PushManager.getInstance().initialize(this);
        if (BuildConfig.DEBUG) {
            //切勿在 release 版本上开启调试日志
            PushManager.getInstance().setDebugLogger(this, new IUserLoggerInterface() {

                @Override
                public void log(String s) {
                    Log.i("PUSH_LOG", s);
                }
            });
        }
    }

    private void initUmengAnalytics() {
        MobclickAgent.setScenarioType(myApplication, MobclickAgent.EScenarioType.E_UM_NORMAL);
    }

    public int getAppCount() {
//        Log.e(TAG, "getAppCount:  current AppCount :" + appCount);
        return appCount;
    }

    public void setAppCount(int appCount) {
        this.appCount = appCount;
    }

    //    初始化Bugly统计
    private void initBugly() {
        Context context = getApplicationContext();
        String packageName = context.getPackageName();
        String processName = getProcessName(android.os.Process.myPid());

        CrashReport.UserStrategy userStrategy = new CrashReport.UserStrategy(context);
        userStrategy.setUploadProcess(processName == null || processName.equals(packageName));
        CrashReport.initCrashReport(context, "b90a3b7a17", false, userStrategy);
    }


    //    获取进程名称
    private String getProcessName(int pid) {

        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;

    }


    /**
     * 添加Activity
     *
     * @param act
     */
    public final void addAct(Activity act) {
        acts.add(act);
    }

    /**
     * 移除Activity
     *
     * @param act
     */
    public final void removeAct(Activity act) {
        acts.remove(act);
        if (act != null) {
            act.finish();
        }
    }

    /**
     * 清除所有存活Activity
     */
    public final void clearAct() {
        for (Activity act : acts) {
            if (act != null) {
                act.finish();
            }
        }
        acts.clear();
    }

    /**
     * 获取当前activity
     *
     * @return
     */
    public Activity getActivity() {
        if (acts.size() > 0) {
            return acts.get(acts.size() - 1);
        } else {
            return null;
        }
    }


    /**
     * 退出程序
     */
    public void exit() {

        clearAct();

        try {
            Runtime.getRuntime().exit(0);
        } catch (Exception e) {
            Runtime.getRuntime().exit(-1);
        }

    }

    public static void logout(Context context) {
        if (!TextUtils.isEmpty(phone)) {
            UserInfoManager.getInstance(getInstance()).saveAccountAndPsd(phone, pwd);
        }
        GlobalConfig.getInstance(myApplication).setLogined(false);
        SerializeUtil.clearChannelInfo();
        MobclickAgent.onProfileSignOff();
        setCurrentModuleType(0);
        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
    }


    public static void clearCache() {

        UserInfoManager.getInstance(myApplication).clear();
        SerializeUtil.clearChannelInfo();
    }


    public static void exitApp() {

        // 用来保存统计数据
        MobclickAgent.onKillProcess(myApplication);

        // kill myself
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
//        MultiDex.install(this);
    }

    public static class PushHandler extends Handler {
        public static final int RECEIVE_MESSAGE_DATA = 0; //接收到消息
        public static final int RECEIVE_CLIENT_ID = 1; //cid通知
        public static final int RECEIVE_ONLINE_STATE = 2; //cid在线状态通知消息
        public static final int SHOW_TOAST = 3; //Toast消息


        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RECEIVE_MESSAGE_DATA:  //接收到消息
                    payloadData.append((String) msg.obj);
                    payloadData.append("\n");


//                    if (demoActivity != null && demoActivity.get() != null) {
//                        if (demoActivity.get().homeFragment != null && demoActivity.get().homeFragment.tvLog != null) {
//                            demoActivity.get().homeFragment.tvLog.append(msg.obj + "\n");
//                        }
//                    }
                    break;

                case RECEIVE_CLIENT_ID:  //cid通知
//                    cid = (String) msg.obj;
//                    if (demoActivity != null && demoActivity.get() != null) {
//                        if (demoActivity.get().homeFragment != null && demoActivity.get().homeFragment.tvClientId != null) {
//                            demoActivity.get().homeFragment.tvClientId.setText((String) msg.obj);
//                        }
//                    }
                    break;
                case RECEIVE_ONLINE_STATE:  //cid在线状态通知
//                    isCIDOnLine = (String) msg.obj;
//                    if (demoActivity != null && demoActivity.get() != null) {
//                        if (demoActivity.get().homeFragment != null && demoActivity.get().homeFragment.tvCidState != null) {
//                            demoActivity.get().homeFragment.tvCidState.setText(msg.obj.equals("true") ? demoActivity.get().getResources().getString(R.string.online) : demoActivity.get().getResources().getString(R.string.offline));
//                        }
//                    }
                    break;
                case SHOW_TOAST:  //需要弹出Toast
//                    Toast.makeText(DemoApplication.appContext, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }

        }

    }
}
